<template>
    <div class="padding-top-20">
        <p class="margin-bottom-20 margin-top-20">房源地址: {{concatLocation(ticket.home_info)}}</p>
        <p class="margin-bottom-20">联系人: {{ticket.subscribe.name}} ({{ticket.subscribe.phone}})</p>
        <Table border :columns="columns" :data="tableData"></Table>

        <Modal title="维修照片" v-model="imgViewer">
            <Row :gutter="20" v-viewer="{movable: false, scalable: false}">
                <i-col :key="id" class="c-ticket__img" span="8" v-for="id in currentImgs">
                    <img :src="'/v3/file/' + id " class="c-ticket__img__item">
                </i-col>
            </Row>
        </Modal>
    </div>
</template>

<script>
import getVal from 'lodash/get'
import cloneDeep from 'lodash/cloneDeep'
import { Poptip, Icon, Tag } from 'iview'; // eslint-disable-line
import { date, dayjs } from '@/libs/date'
import util from '@/libs/util'
import Enum from '@/libs/const'

export default {
  name: 'ticket-base-detail',
  props: {
    ticket: Object
  },
  created () {
    this.setColumns()
  },
  computed: {
    tableData () {
      const { service_type, ticket_devices, ticket_install_devices, replace_devices } = this.ticket
      let result = ticket_devices
      if (service_type === 1) result = this.genInstallDevices(ticket_devices, ticket_install_devices)
      if (service_type === 2) result = this.genRepairDevices(ticket_devices, replace_devices)
      if (service_type === 4) result = ticket_install_devices
      result.forEach(item => {
        item.productModelName = getVal(item, 'device_product.name', '')
        item.deviceModelName = getVal(item, 'device.model', '')
        const teardownReasonState = getVal(item, 'device_state.state')
        item.teardownReason = Enum.teardownReason[teardownReasonState] || ''
        item.isGoodProduct = [4, 6].includes(teardownReasonState)
          ? Enum.isGoodProduct[getVal(item, 'device_state.good_products')] || ''
          : ''
        item.isNewDevice = (item.is_new === undefined || item.is_new === null) ? '' : item.is_new === 1 ? '是' : '否'
      })
      return result
    },
    isCustomerServiceShutdown () {
      return this.ticket && !this.ticket.dispatcher && !this.ticket.implementer && this.ticket.state === 6
    }
  },
  data () {
    const guaranteeColums = {
      title: '保修期',
      render: (h, p) => {
        const device_state = p.row.device_state
        if (!device_state || !device_state.guarantee_begin) return null
        const isNotOverInsurance = dayjs().valueOf() < dayjs(device_state.guarantee_end).valueOf()
        return (
          <div>
            <span>
              {device_state.guarantee_begin} - {device_state.guarantee_end}
            </span>
                        &nbsp;
            {!isNotOverInsurance && <Tag color="red">已过保</Tag>}
          </div>
        )
      }
    }
    return {
      gateways: {},
      imgViewer: false,
      currentImgs: [],
      columns: [],
      baseColumns: [
        { title: '房间名', key: 'room_name' },
        { title: '产品型号', key: 'productModelName' },
        { title: '设备型号', key: 'deviceModelName' },
        { title: '设备SN', key: 'sn' },
        {
          title: '绑定网关',
          render: (h, p) => {
            const { gateway_sn, gateway_name } = p.row
            return (
              <div>
                {gateway_name && <div>名称: {gateway_name}</div>}
                {gateway_sn && <div>sn: {gateway_sn}</div>}
              </div>
            )
          }
        }
      ],
      guaranteeColums,
      teardownColumns: [
        { title: '拆卸说明', key: 'description' },
        { title: '拆卸原因', key: 'teardownReason' },
        { title: '是否良品', key: 'isGoodProduct' }
      ],
      reinstallColumn: { title: '是否为新设备', key: 'isNewDevice' },
      repairbaseColums: [
        {
          title: '设备信息',
          render: (h, p) => {
            if (!p.row.device) return null
            return (
              <div>
                <div>型号: {p.row.device_product && p.row.device_product.name}</div>
                <div>SN: {p.row.sn}</div>
              </div>
            )
          }
        },
        { title: '房间名', key: 'room_name' },
        guaranteeColums,
        { title: '故障时间', render: (h, p) => <span>{date(p.row.fault_time, 'YYYY-MM-DD')}</span> },
        { title: '故障说明', key: 'description' }
      ],
      repairMsgColumns: [
        {
          title: '(客服)故障信息',
          width: 210,
          render: (h, p) => {
            const { row } = p
            if (!row.fault || !this.isCustomerServiceShutdown) return null
            return (
              <div>
                <div><Tag checkable color="red">一级故障</Tag>{row.fault && row.fault.first_name}</div>
                <div><Tag checkable color="red">二级故障</Tag>{row.fault && row.fault.name}</div>
                <div><Tag checkable color="green">解决方案</Tag>{row.solution_name}</div>
              </div>
            )
          }
        },
        {
          title: '(安装师傅)故障信息',
          width: 210,
          render: (h, p) => {
            const { row } = p
            if (!row.fault || this.isCustomerServiceShutdown) return null
            return (
              <div>
                <div><Tag checkable color="red">一级故障</Tag>{row.fault && row.fault.first_name}</div>
                <div><Tag checkable color="red">二级故障</Tag>{row.fault && row.fault.name}</div>
                <div><Tag checkable color="green">解决方案</Tag>{row.solution_name}</div>
              </div>
            )
          }
        },
        {
          title: '新设备信息',
          render: (h, p) => {
            const { new_device_sn } = p.row
            if (!new_device_sn) return null
            return (
              <span>SN: {new_device_sn}</span>
            )
          }
        }
      ],
      pictureColumn: {
        title: '维修照片',
        width: 90,
        render: (h, p) => {
          if (p.row.file_ids.length === 0) return null
          return (
            <i-button size="small" onClick={() => this.handlePic(p.row.file_ids)}>
                            查看
            </i-button>
          )
        }
      }
    }
  },
  methods: {
    concatLocation: util.concatAddress,
    setColumns () {
      let result = []
      if (this.ticket.service_type === 2) {
        result = cloneDeep([...this.repairbaseColums, ...this.repairMsgColumns, this.pictureColumn])
        this.columns = result
      } else {
        if (this.ticket.service_type === 3) result = cloneDeep([this.guaranteeColums, ...this.teardownColumns])
        if (this.ticket.service_type === 4) result = cloneDeep([this.guaranteeColums, this.reinstallColumn])
        this.columns = cloneDeep(this.baseColumns).concat(result)
      }
    },
    genInstallDevices (ticketDevices, ticketInstallDevices) {
      const roomInfo = {}
      const result = []
      // 获取房间下已安装的设备信息
      ticketInstallDevices.forEach(item => {
        if (!roomInfo[item.room_id]) roomInfo[item.room_id] = []
        roomInfo[item.room_id].push(item)
      })
      // 将安装多个设备的房间扁平化
      ticketDevices.forEach(item => {
        const { room_name } = item
        if (!roomInfo[item.room_id]) {
          result.push({room_name})
        } else {
          roomInfo[item.room_id].forEach(installInfo => {
            result.push({
              room_name,
              ...installInfo
            })
          })
        }
      })
      return result
    },
    /**
         * 如果替换了设备
         * ticket_devices的device_id跟sn都会变成新的设备信息
         * replace_devices的device_id对应新的ticket_devices的device_id
         */
    genRepairDevices (ticketDevices, replaceDevices) {
      // console.log(replaceDevices);
      if (!replaceDevices || replaceDevices.length === 0) return ticketDevices
      const replaceDeviceIds = replaceDevices.map(item => item.device_id)
      const result = []
      ticketDevices.forEach(item => {
        /**
                 * 如果ticket_devices子选项是被替换的设备,
                 * 将replace_devices的数据重新整理成ticket_device创建时的设备数据,
                 * 否则直接使用
                 */
        if (replaceDeviceIds.includes(item.device_id)) {
          const replaceData = replaceDevices.find(replaceData => replaceData.device_id === item.device_id)
          item.device_id = replaceData.old_device_id
          item.sn = replaceData.old_device_sn
          item.new_device_id = replaceData.device_id
          item.new_device_sn = replaceData.device_sn
          // console.log(item);
          result.push(item)
        } else {
          result.push(item)
        }
      })
      return result
    },
    handlePic (ids) {
      this.currentImgs = ids
      this.imgViewer = true
    }
  }
}
</script>

<style>
.c-ticket__img {
    position: relative;
    height: 200px;
    background-color: snow;
}

.c-ticket__img__item {
    position: absolute;
    max-width: 100%;
    max-height: 100%;
    left: 50%;
    top: 50%;
    cursor: pointer;
    transform: translate(-50%, -50%);
}
</style>
